package com.chenqi.authentication;

import com.chenqi.properties.LoginResponseType;
import com.chenqi.properties.SecurityProperties;
import com.chenqi.utils.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @description: 自定义成功处理器
 * 可以返回页面或者返回json数据
 * @program: ardai-securtiy-parent
 * @author: ChenQi
 * @create: 2021-03-2021/3/17-14-20
 */
@Component("customAuthenticationSuccessHandler")
//public class CustomAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
public class CustomAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {

    @Autowired
    private SecurityProperties securityProperties;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        //如果配置文件里面修loginType为JSON就执行此返回
        if (LoginResponseType.JSON.equals(securityProperties.getAuthentication().getLoginType())) {
            JsonResult jsonResult = JsonResult.ok("认证成功");
            String string = jsonResult.toJsonString();
            //响应浏览器内容
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(string);
        }else {
            //配置文件里loginType为REDIRECT就执行此返回
            super.onAuthenticationSuccess(request,response,authentication);
        }
}
}
